package com.wans.guli.order.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

@Configuration
public class RabbitMQConfig {

    // 定义 -  用于存放订单关闭的队列 -死信
    @Bean
    public Queue orderDeadQueue() {
        HashMap<String, Object> arguments = new HashMap<>();
        arguments.put("x-message-ttl", 1800000);
        arguments.put("x-dead-letter-exchange", "order.close");
        arguments.put("x-dead-letter-routing-key", "order.close");
        // name:队列名称
        // durable:是否持久化,默认是false,持久化队列：会被存储在磁盘上，当消息代理重启时仍然存在，暂存队列：当前连接有效
        // autoDelete:是否自动删除,当没有生产者或者消费者使用此队列,该队列会自动删除
        // exclusive:是否独占,默认是false,只能有一个消费者监听该队列
        // arguments:可以设置队列的参数，设置队列的参数，比如设置队列的过期时间，或者设置队列的死信队列等
        return new Queue("order.ttl", true, false, false, arguments);
    }

    // 定义 -  用于消费订单关闭的队列
    @Bean
    public Queue orderCloseConsumeQueue() {
        return new Queue("order.close", true);
    }

    // 定义交换机
    @Bean
    public DirectExchange orderDeadExchange() {
        return new DirectExchange("order.create", true, false);
    }

    // 定义交换机
    @Bean
    public DirectExchange orderCloseExchange() {
        return new DirectExchange("order.close", true, false);
    }

    // 绑定死信队列和交换机
    @Bean
    public Binding bindingOrderDead(Queue orderDeadQueue, DirectExchange orderDeadExchange) {
        return BindingBuilder.bind(orderDeadQueue).to(orderDeadExchange).with("order.ttl");
    }

    // 绑定消费死信队列和交换机
    @Bean
    public Binding bindingOrderCloseConsume(Queue orderCloseConsumeQueue, DirectExchange orderCloseExchange) {
        return BindingBuilder.bind(orderCloseConsumeQueue).to(orderCloseExchange).with("order.close");
    }

    // 配置JSON消息转换器
    @Bean
    public MessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }
}